package com.tianji.learning.service.impl;

import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.SectionType;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.utils.LearningRecordDelayTaskHandler;
import javassist.runtime.DotClass;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2024-04-25
 */
@Service
@RequiredArgsConstructor
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {

    private final ILearningLessonService lessonService;
    private final CourseClient courseClient;
    private final LearningRecordDelayTaskHandler taskHandler;

    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        //获取当前登录用户id
        Long userId = UserContext.getUser();
        //查询课表信息 条件user_id和courseId
        LearningLesson lesson = lessonService.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, courseId).one();
        if (lesson == null) {
            throw new BizIllegalException("该课程未加入课表");
        }
        //查询学习记录 条件lesson_id
        List<LearningRecord> list = this.lambdaQuery().eq(LearningRecord::getLessonId, lesson.getId()).list();
        //封装结果返回
        LearningLessonDTO dto = new LearningLessonDTO();
        dto.setId(lesson.getId());
        dto.setLatestSectionId(lesson.getLatestSectionId());
        List<LearningRecordDTO> dtoList = BeanUtils.copyList(list, LearningRecordDTO.class);
        dto.setRecords(dtoList);
        return dto;
    }

    @Override
    public void addLearningRecord(LearningRecordFormDTO dto) {
        //获取当前登录用户id
        Long userId = UserContext.getUser();
        //处理学习记录
        boolean isFinished = false;//代表本小节是否第一次已完成
        if (dto.getSectionType().equals(SectionType.VIDEO)) {
            //提交视频播放记录
            isFinished = handleVideoRecord(userId, dto);
        } else {
            //提交考试记录
            isFinished = handleExamRecord(userId, dto);
        }
        //处理课表数据
        if (!isFinished) {//如果本小节 不是第一次学完 不用处理课程表数据
            return;
        }
        handleLessonData(dto);

    }

    /**
     * @description: 处理课表相关数据
     * @params: [dto, isFinished]
     * @return:
     * @author: ajie
     * @date: 2024/4/27 12:14
     */
    private void handleLessonData(LearningRecordFormDTO dto) {
        //查询课表 learning_lesson 条件 lesson_id 主键
        LearningLesson lesson = lessonService.getById(dto.getLessonId());
        if (lesson == null) {
            throw new BizIllegalException("课表不存在");
        }
        //判断是否是第一次学完 isFinished是不是为true
        boolean allFinished = false;//所有小节是否已经学完

        //远程调用课程服务 得到课程信息 小节总数
        CourseFullInfoDTO cinfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
        if (cinfo == null) {
            throw new BizIllegalException("课程不存在");
        }
        Integer sectionNum = cinfo.getSectionNum();//该课程小小节总数

        //如果 isFinished 为true 本小节第一次学完 判断该用户对该课程下全部小节是否学完
        Integer learnedSections = lesson.getLearnedSections();//当前用户对课程已学的小节数
        allFinished = learnedSections + 1 >= sectionNum;

        //更新课表数据
        lessonService.lambdaUpdate()
                //               .set(lesson.getStatus() == LessonStatus.NOT_BEGIN, LearningLesson::getStatus,LessonStatus.LEARNING)
                .set(lesson.getLearnedSections() == 0, LearningLesson::getStatus, LessonStatus.LEARNING.getValue())
                .set(allFinished, LearningLesson::getStatus, LessonStatus.FINISHED)
                .set(LearningLesson::getLatestSectionId, dto.getSectionId())
                .set(LearningLesson::getLatestLearnTime, dto.getCommitTime())
//                .set(isFinished,LearningLesson::getLearnedSections,lesson.getLearnedSections()+1)
                .setSql("learned_sections = learned_sections + 1")//相对于上面的写法，保证原子性
                .eq(LearningLesson::getId, lesson.getId())
                .update();

    }

    /**
     * @description: 处理视频播放记录
     * @params: [userId, dto]       
     * @return:
     * @author: ajie
     * @date: 2024/4/25 14:48
     */
    private boolean handleVideoRecord(Long userId, LearningRecordFormDTO dto) {
        //查询旧的学习记录 learning_record 条件lessonId section_id
        LearningRecord learningRecord = queryOldRecord(dto.getLessonId(), dto.getSectionId());
//        LearningRecord learningRecord = this.lambdaQuery()
//                .eq(LearningRecord::getLessonId, dto.getLessonId())
//                .eq(LearningRecord::getSectionId, dto.getSectionId())
//                .one();
        //判断是否存在
        if (learningRecord == null) {
            //如果不存在则新增学习记录
            LearningRecord record = BeanUtils.copyBean(dto, LearningRecord.class);
            record.setUserId(userId);
            //保存学习记录learning_record
            boolean result = this.save(record);
            if (!result) {
                throw new DbException("新增视频学习记录失败");
            }
            return false;//代表本小节没有学完
        }
        //如果存在则更新学习记录 learning_record 要更新什么字段 moment
        //判断本小节是否是第一次学完 isFinished为true代表第一次完成
        boolean isFinished = !learningRecord.getFinished() && dto.getMoment() * 2 >= dto.getDuration();
        if (!isFinished) {
            LearningRecord record = new LearningRecord();
            record.setLessonId(dto.getLessonId());
            record.setSectionId(dto.getSectionId());
            record.setMoment(dto.getMoment());
            record.setId(learningRecord.getId());
            record.setFinished(learningRecord.getFinished());
            taskHandler.addLearningRecordTask(record);
            return false;
        }

        //update learning_record set moment = xxx, finished = true, finish_time = xxx where id = xxx
        boolean result = this.lambdaUpdate()
                .set(LearningRecord::getMoment, dto.getMoment())
                .set(isFinished, LearningRecord::getFinished, true)
                .set(isFinished, LearningRecord::getFinishTime, dto.getCommitTime())
                .eq(LearningRecord::getId, learningRecord.getId())
                .update();
        if (!result) {
            throw new DbException("更新视频学习记录失败");
        }

        //清理redis缓存
        taskHandler.cleanRecordCache(dto.getLessonId(), dto.getSectionId());

        return true;
    }

    private LearningRecord queryOldRecord(Long lessonId, Long sectionId) {
        //查询缓存
        LearningRecord cache = taskHandler.readRecordCache(lessonId, sectionId);
        //如果命中直接返回
        if (cache != null) {
            return cache;
        }
        //如果未命中 查询db
        LearningRecord dbRecord = this.lambdaQuery()
                .eq(LearningRecord::getLessonId, lessonId)
                .eq(LearningRecord::getSectionId, sectionId)
                .one();
        //不写判断，writeRecordCache方法可能会报空指针
        if (dbRecord == null) {
            return null;
        }
        //放入缓存
        taskHandler.writeRecordCache(dbRecord);
        return dbRecord;
    }

    /**
     * @description: 处理考试记录
     * @params: [userId, dto]       
     * @return:
     * @author: ajie
     * @date: 2024/4/25 14:37
     */
    private boolean handleExamRecord(Long userId, LearningRecordFormDTO dto) {
        //将dto转换为po
        LearningRecord record = BeanUtils.copyBean(dto, LearningRecord.class);
        record.setUserId(userId);
        record.setFinished(true);//提交考试记录 代表本小节已学完
        record.setFinishTime(dto.getCommitTime());
        //保存学习记录learning_record
        boolean result = this.save(record);
        if (!result) {
            throw new DbException("新增考试记录失败");
        }
        return true;
    }
}
